import glob
import os
import mimetypes
from cuestionarios.forms import *
from cuestionarios.models import *
from gestion_cuestionarios.views import *
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response
from django.core.servers.basehttp import FileWrapper
from django.http import HttpResponse,HttpResponseRedirect

def xml_procs(request, id):
    form=FileForm()
    if "mensaje" in request.COOKIES:
        mensaje=request.COOKIES.get("mensaje", '')
        response=render_to_response('cuestionarios/levantar_xml.html', {'form':form, 'id':id, 'mensaje':mensaje})
        response.delete_cookie("mensaje")
    else:
        response=render_to_response('cuestionarios/levantar_xml.html', {'form':form, 'id':id})
    return response

def get_xml(request, id):
    path='/home/eup/eup/media/'
    c=Cuestionario.objects.get(pk=id)
    filename=c.to_xml(path)
    myfile=c.to_xml(path)
    myfile=open((path+filename), "r")
    content_type_myfile = mimetypes.guess_type(path+filename)[0]
    response = HttpResponse(FileWrapper(myfile), content_type=content_type_myfile)
    response['Content-Disposition'] = 'attachment; filename='+filename
    #response['Content-Disposition'] = 'attachment; filename=a.xml'
    #myfile.close()
    os.remove((path+filename))
    return response
    
def from_xml(request, id):
    if "user" in request.COOKIES:
        userid=request.COOKIES.get("user", '')
    if request.method == 'POST':
        form = FileForm(request.POST, request.FILES)
        if form.is_valid():
            request.FILES['file']
            file=glob.glob('/home/eup/Escritorio/prueba/*.*')
            c=Cuestionario()
            c.user_id=userid
            retorno=c.xml(file[0])
            os.remove(file[0])
            if retorno==None:
                return HttpResponseRedirect(reverse(view_lista_cuestionarios))
            else:
                response=HttpResponseRedirect(reverse(xml_procs, args=[id]))
                response.set_cookie("mensaje", "Error, verifique el archivo XML", 60)
                return response
        else:
            form=FileForm()
            return render_to_response('cuestionarios/levantar_xml.html', {'form':form})
    return HttpResponseRedirect(reverse(view_lista_cuestionarios))